#define _CRT_SECURE_NO_WARNINGS 1
#include "Heap.h"

void HeapInit(HP* hp)
{
	hp->a = NULL;
	hp->size = hp->capacity = 0;
}

bool HeapEmpty(HP* hp)
{
	assert(hp);
	return hp->size == 0;
}

void Swap(HPDataType* px, HPDataType* py)
{
	HPDataType tmp = *px;
	*px = *py;
	*py = tmp;
}

void HeapPush(HP* hp, HPDataType x)
{
	if (hp->size == hp->capacity)//判断是否需要扩容
	{
		int newcapacity = hp->capacity == 0 ? 4 : hp->capacity * 2;
		HPDataType* tmp = (HPDataType*)realloc(hp->a, newcapacity*sizeof(HPDataType));
		assert(tmp);
		hp->a = tmp;
		hp->capacity = newcapacity;
	}
	hp->a[hp->size] = x;
	//AdjustUp(hp->a, hp->size);
	hp->size++;
}

void HeapPrint(HP* hp)
{
	assert(hp);
	for (int i = 0; i < hp->size; i++)
	{
		printf("%d ", hp->a[i]);
	}
	printf("\n");
}

void HeapDestroy(HP* hp)
{
	assert(hp);
	free(hp->a);
	hp->size = hp->capacity = 0;
}

//建立大堆调整
void AdjustUp(HPDataType* a,int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

//小堆建立时调整
void AdjustLow(HPDataType* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

//堆顶元素向下调整(将大的从堆顶降下去)
void HeadTopAdjust(HP* hp)
{
	HPDataType* a = hp->a;
	int parent = 0;
	int child = parent * 2 + 1;
	/*while (a[parent] > a[child] && child < hp->size)双亲节点应与最小的孩子节点比较，所以要在判断最小孩子之后再进行判断
	{
		if (child + 1 < hp->size && a[child+1] < a[child])
		{
			child++;
		}
		Swap(&a[child], &a[parent]);
		parent = child;
		child = parent * 2 + 1;
	}*///错误写法，有bug
    while (child < hp->size)
	{
		if (child + 1 < hp->size && a[child+1] < a[child])
		{
			child++;
		}
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

//删除堆顶元素
void HeapPop(HP* hp)
{
	assert(!HeapEmpty(hp));
	hp->a[0] = hp->a[hp->size - 1];
	hp->size--;
	HeadTopAdjust(hp);
}
